package com.movie.app.utils;

import java.util.ArrayList;
import java.util.Base64;
import java.util.List;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.JsonSerializable.Base;

import org.springframework.context.annotation.Bean;

public class Jwt {
    private String alg = "HmacSHA256";

    public String secret = "123456";

    public String getHeader() {
        JSONObject header = new JSONObject();
        header.put("alg", alg);
        header.put("typ", "JWT");
        String s = header.toJSONString();
        
        return Base64.getEncoder().encodeToString(s.getBytes());
    }

    public String getPayload(String uid) {
        JSONObject payload = new JSONObject();
        payload.put("iss", "admin");
        payload.put("exp", "");
        payload.put("nbf", "");
        payload.put("iat", "");
        payload.put("uid", uid);
        String s = payload.toJSONString();

        return Base64.getEncoder().encodeToString(s.getBytes());
    }

    public String genToken(String uid){
        String header  = getHeader();
        String payload = getPayload(uid);
        String raw     = header + "." + payload;
        String token   = raw + "." + hash_hmac(alg, raw, secret);
        
        return token;
    }
    public String hash_hmac(String alg, String message, String secret){
        try{
            Mac sha256_HMAC = Mac.getInstance(alg);
            SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), alg);
            sha256_HMAC.init(secret_key);
            String hash = Base64.getEncoder().encodeToString(sha256_HMAC.doFinal(message.getBytes()));

            return hash;
        } catch (Exception e){
            return "Error";
        }
        
    }
    public String verifyToken(String token){
        if (token == "") {
            return "null";
        }
        List<String> tokenList = new ArrayList<String>();
        for(String t:token.split("\\.")){
            tokenList.add(t);
        }
        if (tokenList.size()!=3){
            return "null";
        }

        String header    = tokenList.get(0);
        String payload64 = tokenList.get(1);
        String signature = tokenList.get(2);

        String payload = new String(Base64.getDecoder().decode(payload64));
        JSONObject payloadJson = JSONObject.parseObject(payload);

        String expected = hash_hmac(alg, header+"."+payload64, secret);
        if (!expected.equals(signature)) {
            return "null";
        }
        return payloadJson.getString("uid");
    }

}